import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

//import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:kunlun_gas/PublicSource/widgets/media_album_view.dart';
import 'package:permission/permission.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';
import '../../app_files.dart';
import 'dart:io';
import 'dart:core';
import 'navigator_utils.dart';
import 'compress_imagefile.dart';
import '../../config/themeConfig.dart';
import '../../app.dart';
import '../widgets/photo_album_widget.dart';
import '../global_store/state.dart';
import '../global_store/store.dart';
import '../global_store/action.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../widgets/toast_widget.dart';
import '../widgets/webview_config.dart';
import '../widgets/custom_picker_widget.dart';
import '../widgets/custom_dialog.dart';
import '../widgets/custom_edit_widget.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:io' show Platform;
import 'package:flutter/services.dart';
import '../widgets/custom_date_picker.dart';

const double _kPickerSheetHeight = 216.0;

class CommonUtils {
  static double getHeightForStr(String str) {
    double perH = 18.8;
    if (Platform.isAndroid) perH = 18;
    int line = 0;
    if (str.length == 0)
      line = 0;
    else {
      line = str.length ~/ ((ScreenUtil.screenWidthDp - 20) / 13) + 1;
    }
    return perH * line;
  }

  static showToast(BuildContext context, String msg,
      {ToastTipsIconType iconType = ToastTipsIconType.success}) {
    Toast.toast(
      context,
      msg: msg,
      iconType: iconType,
    );
  }

  static showErrorInfo(BuildContext context, String msg) {
    Toast.toast(
      context,
      msg: msg,
      iconType: ToastTipsIconType.info,
    );
  }

  static closeKey(BuildContext context) {
    FocusScope.of(context).requestFocus(FocusNode());
  }

  static getStringWithList(List list, String key) {
    var value;
    for (String str in list) {
      if (str.startsWith(key)) {
        String value = str.substring(key.length + 1);
        if (key == 'title') {
          return Uri.decodeFull(value);
        }
        return value;
      }
    }
    return value;
  }

  static showEditDialog(BuildContext context, String title,
      {TextInputType inputType = TextInputType.text}) {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return CustomDialog(
            backgroundColor: Colors.transparent,
            child: CustomEditWidget(
              title: title,
              inputType: inputType,
            ),
          );
        });
  }

//  static showDetailView(BuildContext context, goods) {
////    Fluttertoast.showToast(msg: '商品详情页 ${goods['id']}');
//    pushRoute(context, RoutePath.goodsDetailView, arguments: goods);
//  }

  static showPhotoAlbumView(BuildContext context,
      {List galleryItems, int initialIndex = 1}) {
    Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => GalleryPhotoViewWrapper(
            galleryItems: galleryItems,
            backgroundDecoration: const BoxDecoration(
              color: Colors.black,
            ),
            initialIndex: initialIndex,
          ),
        ));
  }

  static String checkNullToString(value) {
    return value != null ? value.toString() : '';
  }

  static String getUserLevel(value) {
    Map lv = value['level'];
    return lv == null ? '' : checkNullToString(lv['level']);
  }

  static String formatTime(value) {
    String str = checkNullToString(value);
    DateTime date = DateTime.tryParse(str);
    if (date == null) return str;
    return TimerFormat.formatFromString(str);
  }

  static pushRoute(BuildContext context, String routeName,
      {dynamic arguments}) {
    return Navigator.push(
        context,
        CupertinoPageRoute(
          settings: RouteSettings(name: routeName),
          builder: (context) {
            return AppMainRoutes.routes.buildPage(routeName, arguments);
          },
        ));
  }

  static presentRoute(BuildContext context, String routeName,
      {dynamic arguments}) {
    return Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) {
              return AppMainRoutes.routes.buildPage(routeName, arguments);
            },
            fullscreenDialog: true));
  }

  static presentReplaceRoute(BuildContext context, String routeName,
      {dynamic arguments}) {
    return Navigator.pushReplacement(
        context,
        MaterialPageRoute(
            builder: (context) {
              return AppMainRoutes.routes.buildPage(routeName, arguments);
            },
            fullscreenDialog: true));
  }

  static Widget pageContainer(widget, BuildContext context) {
    return MediaQuery(

        ///不受系统字体缩放影响
        data: MediaQuery.of(context).copyWith(textScaleFactor: 1),
        child: widget);
  }

  static pushReplaceRoute(BuildContext context, String routeName,
      {dynamic arguments}) {
    return Navigator.pushReplacement(context, CupertinoPageRoute(
      builder: (context) {
        return AppMainRoutes.routes.buildPage(routeName, arguments);
      },
    ));
  }

  static Future<Null> showLoadingDialog(BuildContext context) {
    return NavigatorUtils.showGSYDialog(
        context: context,
        child: Material(
            color: Colors.transparent,
            child: WillPopScope(
              onWillPop: () => new Future.value(false),
              child: Center(
                child: new Container(
                  width: 200.0,
                  height: 200.0,
                  padding: new EdgeInsets.all(4.0),
                  decoration: new BoxDecoration(
                    color: Colors.transparent,
                    //用一个BoxDecoration装饰器提供背景图片
                    borderRadius: BorderRadius.all(Radius.circular(4.0)),
                  ),
                  child: new Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      new Container(
                          child: SpinKitCubeGrid(color: Colors.white)),
                      new Container(height: 10.0),
                      new Container(
                          child: new Text(
                        "努力加载中",
                        style: TextStyle(color: Colors.white, fontSize: 18),
                      ))
                    ],
                  ),
                ),
              ),
            )));
  }

//  static showWaitLoading(BuildContext context) {
//    return NavigatorUtils.showLoading(
//      context: context,
//      child: Material(
//        color: Colors.transparent,
//        child: WillPopScope(
//          onWillPop: () => new Future.value(false),
//          child: Center(
//            child: SpinKitCircle(color: ThemeConfig.mainColor),
//          ),
//        ),
//      ),
//    );
//  }

  static showWaitLoading(BuildContext context, {String descText = '正在加载中'}) {
    return NavigatorUtils.showLoading(
      context: context,
      child: Material(
        color: Colors.transparent,
        child: MediaQuery(
          //设置文字大小不随系统设置改变
          data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
          child: WillPopScope(
            onWillPop: () => new Future.value(false),
            child: Center(
              child: Align(
                child: Container(
                  width: 100,
                  height: 100,
                  decoration: BoxDecoration(
                    color: ThemeConfig.rgba(232, 233, 234, 1),
                    borderRadius: BorderRadius.all(Radius.circular(10)),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Theme(
                        data: ThemeData(
                          cupertinoOverrideTheme: CupertinoThemeData(
                            brightness: Brightness.light,
                          ),
                        ),
                        child: CupertinoActivityIndicator(
                          radius: 16,
                        ),
                      ),
                      Padding(padding: EdgeInsets.only(top: 12)),
                      Text(
                        descText,
                        style: TextStyle(
                            color: ThemeConfig.blackColor,
                            fontSize: 13,
                            fontWeight: FontWeight.w500),
                      )
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  static Future showOKCanceltView(BuildContext context, String message,
      {String title = '温馨提示'}) async {
    final ThemeData theme = Theme.of(context);
    final TextStyle dialogTextStyle =
        theme.textTheme.subhead.copyWith(color: theme.textTheme.caption.color);
    Widget _dilog = Platform.isAndroid
        ? AlertDialog(
            title: Text(title),
            content: Text(
              message,
              style: dialogTextStyle,
            ),
            actions: <Widget>[
              FlatButton(
                child: const Text('取消'),
                onPressed: () {
                  Navigator.pop(context, 0);
                },
              ),
              FlatButton(
                child: const Text('确定'),
                onPressed: () {
                  Navigator.pop(context, 1);
                },
              ),
            ],
          )
        : CupertinoAlertDialog(
            title: Text(title),
            content: Text(message),
            actions: <Widget>[
              CupertinoDialogAction(
                child: const Text('取消'),
                onPressed: () {
                  Navigator.pop(context, 0);
                },
              ),
              CupertinoDialogAction(
                child: const Text('确定'),
                onPressed: () {
                  Navigator.pop(context, 1);
                },
              ),
            ],
          );
    int res =
        await NavigatorUtils.showComfirmDialog(context: context, child: _dilog);
    return res;
  }

  static Future showAlertView(BuildContext context, String message,
      {String title = '温馨提示'}) async {
    final ThemeData theme = Theme.of(context);
    final TextStyle dialogTextStyle =
        theme.textTheme.subhead.copyWith(color: theme.textTheme.caption.color);
    Widget _dilog = Platform.isAndroid
        ? AlertDialog(
            title: Text(title),
            content: Text(
              message,
              style: dialogTextStyle,
            ),
            actions: <Widget>[
              FlatButton(
                child: const Text('知道了'),
                onPressed: () {
                  Navigator.pop(context, 1);
                },
              ),
            ],
          )
        : CupertinoAlertDialog(
            title: Text(title),
            content: Text(message),
            actions: <Widget>[
              CupertinoDialogAction(
                child: const Text('知道了'),
                onPressed: () {
                  Navigator.pop(context, 1);
                },
              ),
            ],
          );
    int res =
        await NavigatorUtils.showComfirmDialog(context: context, child: _dilog);
    return res;
  }

  static Future showActionSheet(BuildContext context,
      {String title = '',
      List<String> button,
      bool cancelButton = true,
      int defaultIndex}) async {
    List<Widget> _widget = [];
    for (int i = 0; i < button.length; ++i) {
      _widget.add(CupertinoActionSheetAction(
        isDestructiveAction: (defaultIndex != null && defaultIndex == i),
        child: Text(button[i]),
        onPressed: () {
          Navigator.pop(context, i);
        },
      ));
    }
    Widget _sheet = CupertinoActionSheet(
      title: title.length > 0 ? Text(title) : null,
      message: null,
      actions: _widget,
      cancelButton: cancelButton
          ? CupertinoActionSheetAction(
              child: const Text('取消'),
              isDefaultAction: true,
              onPressed: () {
                Navigator.pop(context, -1);
              },
            )
          : null,
    );
    int res =
        await NavigatorUtils.showActionSheet(context: context, child: _sheet);
    return res;
  }

  static Future showCupertinoDatePicker(
      BuildContext context, DateTime initialDateTime,
      {CupertinoDatePickerMode mode: CupertinoDatePickerMode.date}) async {
    DateTime _dateTime;
    Widget _picker = Container(
      height: _kPickerSheetHeight,
      padding: const EdgeInsets.only(top: 6.0),
      color: CupertinoColors.white,
      child: DefaultTextStyle(
        style: const TextStyle(
          color: CupertinoColors.black,
          fontSize: 22.0,
        ),
        child: GestureDetector(
          // Blocks taps from propagating to the modal sheet and popping.
          onTap: () {},
          child: SafeArea(
            top: false,
            child: CupertinoDatePicker(
              mode: mode,
              use24hFormat: true,
              initialDateTime: initialDateTime,
              onDateTimeChanged: (DateTime newDateTime) =>
                  _dateTime = newDateTime,
            ),
          ),
        ),
      ),
    );
    await NavigatorUtils.showCupertinonDatePicker(
        context: context, child: _picker);
    return _dateTime;
  }

  static Future showCupertinoPicker(BuildContext context, List<String> titles,
      {int initialIndex = 0}) async {
    int _value = initialIndex;
    Widget _picker = Container(
      height: _kPickerSheetHeight,
      padding: const EdgeInsets.only(top: 6.0),
      color: CupertinoColors.white,
      child: DefaultTextStyle(
        style: const TextStyle(
          color: CupertinoColors.black,
          fontSize: 22.0,
        ),
        child: MyPickerWidget(
          titles: titles,
          initialIndex: initialIndex,
          valueChanged: (index) => _value = index,
        ),
      ),
    );
    await NavigatorUtils.showCupertinonDatePicker(
        context: context, child: _picker);
    return _value;
  }

//  static void showToast(String msg) {
//    if (msg.length != 0) Fluttertoast.showToast(msg: msg);
//  }

  static Future<File> showImagePicker(BuildContext context,
      {bool multiPick = false,
      bool cropImg = false,
      bool compressImg = false}) async {
    CommonUtils.closeKey(context);
    if (Platform.isAndroid) {
      List<PermissionName> permissionNames = [];
      permissionNames.add(PermissionName.Camera);
      permissionNames.add(PermissionName.Storage);
      var permissions = await Permission.requestPermissions(permissionNames);
    }

    File _imageFile;
    AssetEntity _assetEntity;
    int res =
        await CommonUtils.showActionSheet(context, button: ['拍摄', '从相册选择']);
    if (res == -1 || res == null) return null;
    if (res == 0) {
      final AssetEntityFile result = await pickFromWxCamera(context);
      if (result != null) {
        _imageFile = result.file;
      }
      else {
        return null;
      }
    }
    try {
      final List<AssetEntity> result = await AssetPicker.pickAssets(
        context,
        maxAssets: 1,
        requestType: RequestType.image,
        gridCount: 4,
        pathThumbSize:
            (((ScreenUtil.screenWidthDp - 8) * window.devicePixelRatio) / 4)
                .ceil(),
        textDelegate: DefaultAssetsPickerTextDelegate(),
      );
      if (result != null && result.isNotEmpty) {
        _assetEntity = result.first;
        _imageFile = await _assetEntity.file;
      }
    } catch (e) {
      showToast(context, '图片选择失败${e}', iconType: ToastTipsIconType.info);
    }

    if (_imageFile == null) {
      return _imageFile;
    }
    File _cropImg;

    if (cropImg) {
      _cropImg = await ImageCropper.cropImage(
        sourcePath: _imageFile.path,
        maxHeight: 1024,
        maxWidth: 1024,
        aspectRatio: CropAspectRatio(ratioX: 1.0, ratioY: 1.0),
      );
    } else
      _cropImg = _imageFile;
    if (compressImg) {
      var _compressImg = await CompressImageFile.compressImageFile(_cropImg);
      print('upload _imageFile : ${_compressImg.lengthSync()}');
      return _compressImg;
    } else
      return _cropImg;
  }

  static showMediaAlbumView(BuildContext context,
      {List files, int initialIndex = 1}) {
    Navigator.push(
      context,
      CustomRoute(
        MediaQuery(
          //设置文字大小不随系统设置改变
          data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
          child: MediaAlbumView(
            files: files,
            initialIndex: initialIndex,
          ),
        ),
      ),
    );
  }

  static Future<AssetEntityFile> pickFromWxCamera(BuildContext c,
      {int type, var info}) async {
    AssetEntity assetEntity = await CameraPicker.pickFromCamera(c,
        enableRecording: true,
        textDelegate: DefaultCameraPickerTextDelegate(),
        maximumRecordingDuration: const Duration(seconds: 60),
        resolutionPreset: ResolutionPreset.high);
    File file, thumbFile;
    if (assetEntity != null) {
      file = await assetEntity.file;
      print(file);
      if (assetEntity.type == AssetType.video) {
        if (Platform.isIOS) {
          CommonUtils.showLoadingDialog(c);
          await Future.delayed(Duration(milliseconds: 1500));
          Navigator.pop(c);
        }
        thumbFile = await CompressImageFile.saveFile(
            await assetEntity.thumbData,
            path: '${DateTime.now().millisecondsSinceEpoch}.jpg');
        return AssetEntityFile(
          file: file,
          assetEntity: assetEntity,
          thumbFile: thumbFile,
        );
      } else {
        if (info == null) {
            return AssetEntityFile(
            file: file,
            assetEntity: assetEntity,
          );
        }
        file = await CommonUtils.pushRoute(c, RoutePath.photoUploadView,
            arguments: {'image': file, 'info': info, 'type': type});
        if (file != null) {
          return AssetEntityFile(
            file: file,
            assetEntity: assetEntity,
          );
        }
      }
    }
    return null;
  }

  static Future<AssetEntityFile> showOrderImagePicker(
    BuildContext context, {
    int type,
    var info,
    bool onlyCamera = true,
  }) async {
    CommonUtils.closeKey(context);
    if (Platform.isAndroid) {
      List<PermissionName> permissionNames = [];
      permissionNames.add(PermissionName.Camera);
      permissionNames.add(PermissionName.Storage);
      var permissions = await Permission.requestPermissions(permissionNames);
    }

    File _imageFile;
    AssetEntity _assetEntity;
    int res = await CommonUtils.showActionSheet(context,
        button: onlyCamera ? ['拍摄'] : ['拍摄', '从相册选择']);
    if (res == -1 || res == null) return null;
    if (res == 0) {
      return pickFromWxCamera(context, info: info, type: type);
    }
    try {
      final List<AssetEntity> result = await AssetPicker.pickAssets(
        context,
        maxAssets: 1,
        requestType: RequestType.common,
        gridCount: 4,
        pathThumbSize:
            (((ScreenUtil.screenWidthDp - 8) * window.devicePixelRatio) / 4)
                .ceil(),
        textDelegate: DefaultAssetsPickerTextDelegate(),
      );
      if (result != null && result.isNotEmpty) {
        _assetEntity = result.first;
        _imageFile = await _assetEntity.file;
        if (_imageFile.readAsBytesSync().lengthInBytes > 30 * 1024 * 1024) {
          CommonUtils.showErrorInfo(context,
              '选择${result.first.type == AssetType.video ? '视频' : '图片'}过大,请重新选择或手动录制');
          return null;
        }
        if (result.first.type != AssetType.image) {
          File thumbFile = await CompressImageFile.saveFile(
              await _assetEntity.thumbData,
              path: '${DateTime.now().millisecondsSinceEpoch}.jpg');
          return AssetEntityFile(
            file: _imageFile,
            assetEntity: _assetEntity,
            thumbFile: thumbFile,
          );
        }
      }
    } catch (e) {
      showToast(context, '图片选择失败${e}', iconType: ToastTipsIconType.info);
    }
    if (_imageFile != null) {
      _imageFile = await CommonUtils.pushRoute(
          context, RoutePath.photoUploadView,
          arguments: {'image': _imageFile, 'info': info, 'type': type});
      if (_imageFile != null) {
        return AssetEntityFile(
          file: _imageFile,
          assetEntity: _assetEntity,
        );
      }
    }
    return null;
  }

  static checkUserLogin(BuildContext context, Function isLogin) {
    GlobalState state = GlobalStore.store.getState();
    if (state.userInfo.userid.length == 0) {
      gotoLoginView(context);
    } else {
      isLogin();
    }
  }

  static setStaffLoginDefaultInfo({
    String account,
    String password,
    String roleName,
  }) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    if (account != null) prefs.setString('staffAccount', account);
    if (password != null) prefs.setString('staffPassword', password);
    if (roleName != null) prefs.setString('staffRoleName', roleName);
  }

  static gotoLoginView(BuildContext context) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    String phone = prefs.getString('staffAccount');
    String password = prefs.getString('staffPassword');
    String roleName = prefs.getString('staffRoleName');
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) {
              return AppMainRoutes.routes.buildPage(RoutePath.staffLoginView, {
                'phone': phone,
                'password': password,
                'roleName': roleName,
              });
            },
            fullscreenDialog: true));
  }

//  static showShareView(BuildContext context, var goodsInfo) {
//    return showModalBottomSheet(
//        context: context,
//        builder: (BuildContext context) {
//          return AppMainRoutes.routes.buildPage(RoutePath.shareView, goodsInfo);
//        },
//        isScrollControlled: true,
//        backgroundColor: Colors.transparent);
//  }

  static showVersionDialog(BuildContext context,
      {String message, bool isForce = false, String url}) {
    final ThemeData theme = Theme.of(context);
    final TextStyle dialogTextStyle =
        theme.textTheme.subhead.copyWith(color: theme.textTheme.caption.color);
    Widget _dilog = WillPopScope(
      child: AlertDialog(
        title: Text('发现新版本'),
        content: Text(
          message,
          style: dialogTextStyle,
        ),
        actions: <Widget>[
          isForce
              ? Container()
              : FlatButton(
                  child: const Text('取消'),
                  onPressed: () {
                    Navigator.pop(context, 0);
                  },
                ),
          FlatButton(
            child: const Text('确定'),
            onPressed: () {
              isForce
                  ? bus.emit('forceUpdate', url)
                  : Navigator.pop(context, 1);
            },
          ),
        ],
      ),
      onWillPop: () => new Future.value(false),
    );
    return NavigatorUtils.showGSYDialog(context: context, child: _dilog);
  }

  static String getDistanceStr(String original) {
    double distance = double.tryParse(original);
    if (distance == null) return '未知';
    if (distance > 1000) {
      return '${(distance / 1000.0).toStringAsFixed(2)}Km';
    } else
      return '${original}m';
  }

  static pushUserCenter(BuildContext context, String userId) {
    pushRoute(context, RoutePath.userCenterView, arguments: {
      'isUser': false,
      'userId': userId,
    });
  }

  static Future pushWebViewFlutterPage(
    BuildContext context,
    String title,
    String url, {
    WebViewConfigModel webInfo = const WebViewConfigModel(),
  }) {
    if (!url.startsWith('http')) url = WebUrlConfig.htmlURL + url;

    Widget _child = AppMainRoutes.routes.buildPage(
      RoutePath.webView_FlutterView,
      {'url': url, 'title': title, 'webInfo': webInfo},
    );
    return Navigator.push(
      context,
      CupertinoPageRoute(
        builder: (context) {
          return Material(
              color: ThemeConfig.mainColor,
              child: Container(
                child: _child,
              ));
        },
      ),
    );
  }

  static showLocationNavigation(
      double lat, double lng, BuildContext context) async {
    List _list = [];
    String url;
    if (Platform.isIOS) {
      var url = 'http://maps.apple.com/?daddr=$lat,$lng&address=';
      url = Uri.encodeFull(url);
      _list.add({'苹果地图': url});
    }
    bool amapIOS = await canLaunch('iosamap://');
    if (amapIOS) {
      url =
          'iosamap://navi?sourceApplication=amap&backScheme=com.australia.mc&lat=$lat&lon=$lng&dev=0&style=2';
      url = Uri.encodeFull(url);
      _list.add({'高德地图': url});
    }
    bool amapAdv = await canLaunch('androidamap://');
    if (amapAdv) {
      url =
          'androidamap://navi?sourceApplication=amap&backScheme=com.australia.mc&lat=$lat&lon=$lng&dev=0&style=2';
      url = Uri.encodeFull(url);
      _list.add({'高德地图': url});
    }
    bool googleMap = await canLaunch('androidamap://');
    if (googleMap) {
      url =
          'comgooglemaps://?x-source=googlemaps&x-success=com.australia.mc&saddr=&daddr=$lat,$lng&directionsmode=driving';
      url = Uri.encodeFull(url);
      _list.add({'谷歌地图': url});
    }

    bool qqMap = await canLaunch('qqmap://');
    if (qqMap) {
      url =
          'qqmap://map/routeplan?type=drive&fromcoord=CurrentLocation&tocoord=$lat,$lng&referer=FN4BZ-6E33P-LFTDB-VRZ4C-NTP3Z-RVFFK&debug=true&to=';
      _list.add({'腾讯地图': url});
    }

    bool baiduMap = await canLaunch('baidumap://');
    if (baiduMap) {
      url =
          'baidumap://map/direction?destination=name:|latlng:$lat,$lng&coord_type=bd09ll&mode=driving';
      url = Uri.encodeFull(url);
      _list.add({'百度地图': url});
    }
    if (_list.length == 0) {
      showErrorInfo(context, '未检测地图软件');
    } else {
      List<String> _titles = _list.map<String>((var data) {
        return data.keys.elementAt(0);
      }).toList();
      int res = await showActionSheet(context, title: '导航', button: _titles);
      if (res != null && res != -1) {
        Map data = _list[res];
        launch(data.values.elementAt(0));
      }
    }
  }

  static setPubDefaultValue({
    String phone,
    String password,
  }) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    if (phone != null) prefs.setString('editPhone', phone);
    if (password != null) prefs.setString('editPassword', password);
  }

  static getPubDefaultValue(String key) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString(key);
  }

  static callPhone(String phone, BuildContext context) async {
    var res = await CommonUtils.showActionSheet(context,
        title: '联系电话：$phone', button: ['拨打']);
//    if (res == 0) {
//      await Clipboard.setData(ClipboardData(text: phone));
//      CommonUtils.showToast(context, '已复制到剪切板');
//    }
    if (res == 0) {
      var confirm = await CommonUtils.showOKCanceltView(context, '确认拨打电话?');
      if (confirm == 1) launch("tel://$phone");
    }
  }

  static showSearchView(
    BuildContext context, {
    int type,
    String heroTag = 'search',
    String communityID,
    String communityName,
    String planID,
    String workID,
    int status = 0,
  }) {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) {
              return AppMainRoutes.routes.buildPage(RoutePath.searchView, {
                'type': type,
                'tag': heroTag,
                'communityID': communityID,
                'communityName': communityName,
                'planID': planID,
                'workID': workID,
                'status': status,
              });
            },
            fullscreenDialog: true));
  }

  static showMyDatePicker(
    BuildContext context, {
    String desc = '请选择',
    DateTime initialDateTime,
    DateTime minimumDate,
    DateTime maximumDate,
    CupertinoDatePickerMode mode: CupertinoDatePickerMode.date,
  }) async {
    DateTime _dateTime;
    Widget _picker = MyDatePicker(
      desc: desc,
      initialDateTime: initialDateTime,
      minimumDate: minimumDate,
      maximumDate: maximumDate,
      model: mode,
      onDateTimeChanged: (DateTime newDateTime) => _dateTime = newDateTime,
    );
    await NavigatorUtils.showCupertinonDatePicker(
        context: context, child: _picker);
    return _dateTime;
  }

  static initImageConfig({token, bool isGasUser}) async {
    ResultData imgUrlRes = await CommonNetWork.getImageConfig(token: token);
    if (imgUrlRes.success) {
      List data = imgUrlRes.data;
      Map config = data.first;
      List value = config['ConfigValue'];
      value.forEach((element) {
        if (element['Key'] == 'imgScan') {
          GlobalStore.store.getState().imageUrl = element['Value'];
        }
        if (element['Key'] == 'imgUpload') {
          GlobalStore.store.getState().uploadUrl = element['Value'];
        }
      });
    }
  }

  static routeBuildPage(
      BuildContext context, String routeName, dynamic arguments) {
    return MediaQuery(
      //设置文字大小不随系统设置改变
      data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
      child: AppMainRoutes.routes.buildPage(routeName, arguments),
    );
  }
}
